package com.xbkj.pgrp.server.model.common.pk;

import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.erupt.core.util.EruptSpringUtil;
import xyz.erupt.jpa.dao.EruptDao;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;

public class GenericPk implements IdentifierGenerator {

    private static  final Logger logger = LoggerFactory.getLogger(GenericPk.class);


    @Override
    public Serializable generate(SharedSessionContractImplementor sharedSessionContractImplementor, Object o) throws HibernateException {
        SeriesModel seriesModel = null;
        EruptDao eruptDao = EruptSpringUtil.getBean(EruptDao.class);
        try {

            seriesModel = eruptDao.findById(SeriesModel.class, o.getClass().getName());

        }catch (Exception e) {
            logger.error("获取序列失败",e);
        }
        if (null == seriesModel) {
            seriesModel = new SeriesModel();
            seriesModel.setType(o.getClass().getName());
            seriesModel.setSeries(1L);
            seriesModel.setDate(new SimpleDateFormat("yyyyMMdd").format(new Date()));
        } else {
            if (seriesModel.getSeries() >= 9000) {
                seriesModel.setDate(new SimpleDateFormat("yyyyMMdd").format(new Date()));
                seriesModel.setSeries(1L);
            } else {
                seriesModel.setSeries(seriesModel.getSeries() + 1);
            }
        }
        eruptDao.persistAndFlush(seriesModel);
        return Long.valueOf(new SimpleDateFormat("yyyyMMdd").format(new Date())
                +String.format("%05d", seriesModel.getSeries()));
    }
}
